package com.qf.cx.simplenms.report.receiver.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.qf.cx.simplenms.monitor.model.HeartBeatReport;
import com.qf.cx.simplenms.report.model.Report;

@RestController
@RequestMapping(path = "/receiver")
public class ReceiveController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@RequestMapping(path = "/report", method = RequestMethod.POST)
	public void report(@RequestBody Report report) {
		Gson g = new Gson();

		Date date = new Date(report.getReportCreateTime());
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS");

		System.out.println(g.toJson(report));
		File file = new File("report");
		file.mkdir();
		file = new File(file, report.getTopic() + "-" + df.format(date) + ".json");

		try (FileOutputStream fileOutputStream = new FileOutputStream(file, true);) {
			fileOutputStream.write(g.toJson(report).getBytes("UTF-8"));
		} catch (IOException e) {
			logger.error("Could not write to file ", e);
		}
	}

	@RequestMapping(path = "/status", method = RequestMethod.POST)
	public void status(@RequestBody HeartBeatReport report) {
		Gson g = new Gson();

		Date date = new Date(report.getReportCreateTime());
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS");

		System.out.println(g.toJson(report));
		File file = new File("status");
		file.mkdir();
		file = new File(file, df.format(date) + ".json");

		try (FileOutputStream fileOutputStream = new FileOutputStream(file, true);) {
			fileOutputStream.write(g.toJson(report).getBytes("UTF-8"));
		} catch (IOException e) {
			logger.error("Could not write to file ", e);
		}
	}
}